﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.SignalR;
using RoadFlow.Utility;
using RoadFlow.Mapper;

namespace RoadFlow.Mvc.Controllers
{
    public class TestController : Controller
    {
      
        public TestController()
        {
           
        }
        public IActionResult Index()
        {
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();//开始记录时间
            var flowtasks = new List<Model.FlowTask>();

            var obj = Cache.IO.Get("test");
            if (null == obj)
            {
                using (var db = new DataContext())
                {
                    flowtasks = db.QueryAll<Model.FlowTask>();
                    Cache.IO.Insert("test", flowtasks);
                }
            }
            else
            {
                flowtasks = obj as List<Model.FlowTask>;
                ViewData["msg"] = "缓存";
            }

                sw.Stop();//结束记录时间
            //@Html.Raw("程序的运行时间：" + sw.Elapsed.Seconds + " 秒<br/>");
            //ViewData["msg"]= "程序的运行时间：" + sw.Elapsed.Milliseconds + " 毫秒--"+ flowtasks.Count;
            return View();
        }

        public IActionResult Test()
        {
            ViewData["test"] = HttpContext.Session.GetString("test");
            return View();
        }

        /// <summary>
        /// 自定义表单
        /// </summary>
        /// <returns></returns>
        public IActionResult CustomForm()
        {
            string instanceid = Request.Querys("instanceid");
            System.Data.DataTable dt = new System.Data.DataTable();
            if (!instanceid.IsNullOrWhiteSpace())
            {
                using (var db = new DataContext())
                {
                    dt = db.GetDataTable("select * from rf_test where id={0}", instanceid);
                }
            }
            return View(dt);
        }
        /// <summary>
        /// 保存自定义表单
        /// </summary>
        /// <returns></returns>
        public string SaveCustomForm()
        {
            string instanceid = Request.Querys("instanceid");
            string title = Request.Forms("Title");
            string Contents = Request.Forms("Contents");
            string sql = instanceid.IsNullOrWhiteSpace() ?
                "insert into RF_Test(Id,F1,F2) values({0},{1},{2})" :
                "update rf_test set f1={0},f2={1} where id={2}";
            Guid id = Guid.NewGuid();
            using (var db = new DataContext())
            {
                if (instanceid.IsNullOrWhiteSpace())
                {
                    db.Execute(sql, id, title, Contents);
                }
                else
                {
                    db.Execute(sql, title, Contents, instanceid);
                }
                db.SaveChanges();
            }
            Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
            {
                { "success", 1 },
                { "message", "保存成功" },
                { "instanceid", id.ToString() },
                { "title", title }
            };
            return jObject.ToString(Newtonsoft.Json.Formatting.None);
        }

        /// <summary>
        /// 测试流程提交前事件
        /// </summary>
        /// <param name="eventParam"></param>
        public string FlowSubmitBefor(Model.FlowRunModel.EventParam eventParam)
        {
            Business.Log.Add("进入了流程提交前事件-" + eventParam.TaskTitle, eventParam.ToString(), Business.Log.Type.其它);
            return "1";//如果返回非1的字符串，会弹出字符串提示，并且流程不能提交。
        }

        /// <summary>
        /// 测试流程提交后事件
        /// </summary>
        /// <param name="eventParam"></param>
        public void FlowSubmitAfter(Model.FlowRunModel.EventParam eventParam)
        {
            Business.Log.Add("进入了流程提交后事件-" + eventParam.TaskTitle, eventParam.ToString(), Business.Log.Type.其它);
        }

        /// <summary>
        /// 子流程激活前事件
        /// </summary>
        /// <param name="eventParam"></param>
        public string SubFlowActive(Model.FlowRunModel.EventParam eventParam)
        {
            //可以在这里将主流程数据转入到子流程表
            string id = Guid.NewGuid().ToString();
            string title = "子流程测试-" + eventParam.TaskTitle;
            string sql = "insert into RF_Test(Id,f1) values({0},{1})";
            using (var db = new DataContext())
            {
                db.Execute(sql, id, title);
                db.SaveChanges();
            }
            Newtonsoft.Json.Linq.JObject jObject = new Newtonsoft.Json.Linq.JObject
            {
                { "instanceId", id },
                { "title", title }
            };
            return jObject.ToString();
        }

        /// <summary>
        /// 子流程完成后事件
        /// </summary>
        /// <param name="eventParam"></param>
        public string SubFlowCompleted(Model.FlowRunModel.EventParam eventParam)
        {
            Business.Log.Add("执行了子流程完成后事件", eventParam.ToString());
            return "1";
        }

        /// <summary>
        /// 跳过步骤方法
        /// </summary>
        /// <param name="eventParam"></param>
        /// <returns>方法可以返回string的"1"或者int的1或者bool的true都表示要跳过，返回其它值为不跳过</returns>
        public bool StepSkip(Model.FlowRunModel.EventParam eventParam)
        {
            var currentTask = (Model.FlowTask)eventParam.Other;
            return false;
        }

        /// <summary>
        /// 测试应用程序生成器自定义显示
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        public string ProgramShow(System.Data.DataRow dr)
        {
            return "custom-" + dr["f15"].ToString();
        }

        public string TestOptions()
        {
            return "<option value='1'>test1</option><option value='2'>test2</option><option value='3'>test3</option>";
        }

        public string TestOptions1()
        {
            return "<option value='1'>test1</option><option value='2'>test2</option><option value='3'>test3</option>";
        }

        /// <summary>
        /// 测试得到数据表格
        /// </summary>
        /// <returns></returns>
        public string GetTableHtml(object param)
        {
            Newtonsoft.Json.Linq.JArray formData = (Newtonsoft.Json.Linq.JArray)param;
            //if (Request.Method.EqualsIgnoreCase("post"))
            //{
            //    string formdata = Request.Form["a"];
            //    Newtonsoft.Json.Linq.JArray formData = Newtonsoft.Json.Linq.JArray.Parse(formdata);
            //}
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            stringBuilder.Append("<table width='99%' align='center'><thead><tr>");
            stringBuilder.Append("<th>列1</th>");
            stringBuilder.Append("<th>列2</th>");
            stringBuilder.Append("<th>列3</th>");
            stringBuilder.Append("<th>列4</th>");
            stringBuilder.Append("<th>列5</th>");
            stringBuilder.Append("<th>列6</th>");
            stringBuilder.Append("</tr></thead>");
            stringBuilder.Append("<tbody><tr>");
            stringBuilder.Append("<td>" + "" + "</td>");
            stringBuilder.Append("<td>行2</td>");
            stringBuilder.Append("<td>行3</td>");
            stringBuilder.Append("<td>行4</td>");
            stringBuilder.Append("<td>行5</td>");
            stringBuilder.Append("<td>行6</td>");
            stringBuilder.Append("</tr></tbody>");
            stringBuilder.Append("</table>");

            return stringBuilder.ToString();
        }
    }
}